#include "yingcewindow.h"
#include "actionmanager.h"
#include "home/homeview.h"
#include "libs/controls/toastlabel.h"
#include "main/mainview.h"
#include "usersettings.h"
#include "utils/initializationtask.h"
#include "utils/logintask.h"
#include "yingce.h"
#include <QFrame>
#include <QMenuBar>
#include <QPushButton>
#include <QResizeEvent>
#include <QStatusBar>
#include <QVBoxLayout>

YingCeWindow* YingCeWindow::instance_ = nullptr;

YingCeWindow::YingCeWindow(QWidget* parent) : QMainWindow { parent }
{
    Q_ASSERT(!instance_);
    instance_ = this;

    setWindowTitle(tr("YingCe"));
    setWindowIcon(QIcon(":/images/yingce.png"));
    setMinimumSize(800, 600);
    resize(1024, 768);

    QFrame* client = new QFrame(this);
    setCentralWidget(client);

    QHBoxLayout* hl = new QHBoxLayout(client);
    hl->setContentsMargins(0, 0, 0, 0);
    hl->setSpacing(0);

    home_view_ = new HomeView(client);
    hl->addWidget(home_view_);

    QMenuBar* menu_bar = new QMenuBar(this);
    menu_bar->addMenu(ActionManager::instance()->buildFileMenu(this));
    menu_bar->addMenu(ActionManager::instance()->buildHelpMenu());
    setMenuBar(menu_bar);

    if (UserSettings::instance().loginUser().autoLogin()
        && UserSettings::instance().loginUser().isValid()) {
        home_view_->setEnabled(false);

        LoginTask* t = new LoginTask(UserSettings::instance().loginUser(), this);
        connect(t, &LoginTask::finished, this, &YingCeWindow::onLoginFinished);
        connect(t, &LoginTask::failed, this, [this](int error, const QString& msg) {
            Q_UNUSED(error)
            sender()->deleteLater();
            yc::ToastLabel::showMessage(msg, this);
            if (home_view_)
                home_view_->setEnabled(true);
        });
        YingCe::instance()->authTaskQueue()->addTask(t);
    }

    connect(home_view_, &HomeView::finished, this, &YingCeWindow::onLoginFinished);
}

YingCeWindow::~YingCeWindow()
{
    instance_ = nullptr;
}

void YingCeWindow::registerUser()
{
    if (home_view_) {
        home_view_->registerUser();
    }
}

void YingCeWindow::logout()
{
    if (main_view_) {
        main_view_->hide();
        main_view_->deleteLater();
        main_view_ = nullptr;
    }
    if (!home_view_) {
        home_view_ = new HomeView(centralWidget());
        connect(home_view_, &HomeView::finished, this, &YingCeWindow::onLoginFinished);
        centralWidget()->layout()->addWidget(home_view_);
        home_view_->show();
    }
}

void YingCeWindow::requestStop(const yc::ResolveCallback& resolve, const yc::RejectCallback& reject)
{
    if (main_view_) {
        main_view_->requestStop(resolve, reject);
    } else {
        if (resolve) {
            resolve();
        }
    }
}

void YingCeWindow::closeEvent(QCloseEvent* e)
{
    if (main_view_) {
        auto resolve = [this, e] {
            // save window state
            UserSettings::instance().setWindowState(windowState());
            UserSettings::instance().setWindowRect(geometry());
            QMainWindow::closeEvent(e);
        };
        auto reject = [e] { e->ignore(); };
        main_view_->requestStop(resolve, reject);
    } else {
        // save window state
        UserSettings::instance().setWindowState(windowState());
        UserSettings::instance().setWindowRect(geometry());
        QMainWindow::closeEvent(e);
    }
}

void YingCeWindow::onLoginFinished()
{
    Q_ASSERT(home_view_);
    home_view_->setEnabled(false);

    auto f = [this] {
        disconnect(sender(), nullptr, this, nullptr);
        main_view_ = new MainView(centralWidget());
        centralWidget()->layout()->addWidget(main_view_);
        main_view_->show();
    };

    InitializationTask* t = new InitializationTask(this);
    connect(t, &InitializationTask::finished, home_view_, &HomeView::deleteLater);
    connect(t, &InitializationTask::failed, home_view_, &HomeView::deleteLater);
    connect(t, &InitializationTask::finished, this, f);
    connect(t, &InitializationTask::failed, this, f);
    t->start();
}
